// pages/goods_list/goods_list.js
import { request} from "../../request/index.js"
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs:[
      {id:0,value:"综合",isActive:true},
      {id:1,value:"销量",isActive:false},
      {id:2,value:"价格",isActive:false},
    ],
    goods_list:[]
  },
  //接口需要的参数
  QueryParams:{
    query:"",
    cid:"",
    pagenum:"",
    pagesize:10,
  },
  //总页数，起始为1
  totalPages:1,
 
  onLoad: function (options) {
    this.QueryParams.cid=options.cid;
    this.getGoodsList();
  },

  //获取商品列表数据
  async getGoodsList(){
    const res=await request({url:"/goods/search",data:this.QueryParams});
    //console.log(res);
    //返回一个{total:23,pagenum:1,goods:Array(10)}对象
    const total=res.total;
    this.totalPages=Math.ceil(total/this.QueryParams.pagesize)
    this.setData({
      // 解构原goods_List并拼接上res.goods的数据
      goods_list:[...this.data.goods_list,...res.goods]
    })

    // 手动关闭下拉刷新窗口
    wx.stopPullDownRefresh();
  },

  //更换导航栏
  handleTabsItemChange(e){
    const {index}=e.detail;
    let {tabs}=this.data;
    tabs.forEach((v,i)=>i===index?v.isActive=true:v.isActive=false);
    this.setData({
      tabs
    })
  },

  // 上滑触底事件
  onReachBottom(){
    if(this.QueryParams.pagenum>=this.totalPages){
      wx.showToast({
        title: '已经到底了',
        icon:"error"
      })
    }
    else{
      this.QueryParams.pagenum++;
      this.getGoodsList();
    }
  },
  
  //下拉刷新事件
  onPullDownRefresh(){
    //重新置空数组、重置页码、重发请求
    this.setData({goods_list:[]});
    this.QueryParams.pagenum=1;
    this.getGoodsList();
  }
})